﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WebUI.Models;
using System.Web.Security;
using System.Linq.Expressions;

namespace WebUI.Controllers
{
    [Authorize(Roles = "Admin,Engineer")]
    [GZip()]
    public class SystemMgrController : _SiteBaseController
    {
        //public ActionResult CheckEnumUsing(string id)
        //{
        //    var ed=DB.EnumDefines.FirstOrDefault(v => v.EnumID == id);
        //    ed.EnumValues.SelectMany(v => v.QizItems).Count() > 0;
        //    bool edu = ed.QizItems.Count>0;
        //    foreach (var item in ed.EnumValues)
        //    {
        //        ed.EnumValues.SelectMany(v => v.QizItems).Count()>0;
        //    }

        //}
        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            ViewBag.Status = DB.EnumValues.Where(v => v.EnumID == "01001");
            ViewBag.Types = DB.EnumValues.Where(v => v.EnumID == "01002");
            ViewBag.utid = Request["utid"];
            ViewBag.CurrentHosp = Request["hid"];
            ViewBag.CurrentDep = Request["did"];
            ViewBag.CurrentSubj = Request["sid"];
            ViewBag.CurrentBingQu = Request["bid"];
            ViewBag.Doctors = DB.Doctors;
            ViewBag.Departments = DB.Departments;
            ViewBag.Users = DB.Doctors;
            ViewBag.Bingqus = DB.BingQus;
            ViewBag.Hospitals = DB.Hospitals_Fixed;
            Response.Cache.SetExpires(DateTime.MinValue);

            base.OnActionExecuting(filterContext);
        }

        public ActionResult Index() { return RedirectToAction("HospAndDepartMgr"); }
        //
        // GET: /SystemMgr/
        public ActionResult HospAndDepartMgr(string act, string sid, string utid)
        {

            if (!string.IsNullOrEmpty(act))
            {
                string[] vs = sid.Split('_');
                if (act == "d")
                {
                    if (vs[0] == "h") return RedirectToAction("DelHospital", new { ID = vs[1], utid = utid });
                    if (vs[0] == "b") return RedirectToAction("DelBingQu", new { ID = vs[1], utid = utid });
                    if (vs[0] == "d") return RedirectToAction("DelDepartment", new { ID = vs[1], utid = utid });
                    if (vs[0] == "s") return RedirectToAction("SFDDelete", new { ID = vs[1], utid = utid });
                }
                else if (act == "n")
                {
                    if (vs[0] == "r") return RedirectToAction("HospitalEdit", new { ID = string.Empty, utid = utid });
                    if (vs[0] == "h") return RedirectToAction("EditBingQu", new { ID = string.Empty, HospitalID = vs[1], utid = utid });
                    if (vs[0] == "b") return RedirectToAction("EditDepartment", new { ID = string.Empty, BingQuID = vs[1], utid = utid });
                    if (vs[0] == "d") return RedirectToAction("SFDEdit", new { ID = string.Empty, DepID = vs[1], utid = utid });
                }
                else if (act == "e")
                {
                    if (vs[0] == "h") return RedirectToAction("HospitalEdit", new { ID = vs[1], utid = utid });
                    if (vs[0] == "b") return RedirectToAction("EditBingQu", new { ID = vs[1], HospitalID = string.Empty, utid = utid });
                    if (vs[0] == "d") return RedirectToAction("EditDepartment", new { ID = vs[1], BingQuID = string.Empty, utid = utid });
                    if (vs[0] == "s") return RedirectToAction("SFDEdit", new { ID = vs[1], DepID = string.Empty, utid = utid });
                }
                else if (act == "x")
                {
                    //sf36 特殊处理，只有病区及department.
                    if (vs[0] == "d") return RedirectToAction("NewSF36", new { DepID = vs[1], utid = utid });
                }
            }
            return View();
        }

        public ActionResult Hospitals()
        {
            return PartialView(DB.Hospitals_Fixed);
        }

        [HttpGet]
        public ActionResult HospitalEdit(string ID)
        {
            if (string.IsNullOrEmpty(ID)) return PartialView(DB.Hospitals.CreateObject());
            else return PartialView(DB.Hospitals.Where(v => v.HospitalID == ID).FirstOrDefault());
        }

        [HttpPost]
        public ActionResult HospitalEdit(Models.Hospital m)
        {
            if (ModelState.IsValid)
            {
                if (string.IsNullOrEmpty(m.HospitalID))
                {
                    m.HospitalID = DB.NewID();
                    DB.Hospitals.AddObject(m);
                }
                else
                {
                    DB.Hospitals.Where(v => v.HospitalID == m.HospitalID).First();
                    DB.Hospitals.ApplyCurrentValues(m);
                }
                DB.SaveChanges();

                return RedirectToAction("Hospitals", new { hid = m.HospitalID });
            }
            else
            {
                throw new ArgumentException("输入不正确。");
            }
        }

        [HttpGet]
        public ActionResult DelHospital(string ID)
        {
            var m = DB.Hospitals.Where(v => v.HospitalID == ID).SingleOrDefault();
            DB.DeleteObject(m);
            DB.SaveChanges();
            ViewBag.UpdateMode = "Delete";
            return RedirectToAction("Hospitals");

        }
        /////////////////////

        public ActionResult Departments(string HospitalID)
        {
            //ViewBag.HospitalID = HospitalID;
            return PartialView(DB.Hospitals.Where(v => HospitalID == null ? true : v.HospitalID == HospitalID).FirstOrDefault());
            //return RedirectToAction("hospitals");
        }


        //[HttpGet]
        //public ActionResult DepartmentItem()
        //{
        //    return PartialView();
        //}

        //[HttpPost]
        //public ActionResult DepartmentItem(Models.Department m)
        //{
        //    if (ModelState.IsValid)
        //    {
        //        m.DepartmentID = DB.NewID();
        //        DB.Departments.AddObject(m);
        //        DB.SaveChanges();

        //        return RedirectToAction("Departments");
        //    }
        //    else
        //    {
        //        throw new ArgumentException("输入不正确。");
        //    }
        //}

        [HttpGet]
        public ActionResult EditBingQu(string ID, string HospitalID)
        {
            var m = string.IsNullOrEmpty(ID) ? new BingQu() { HospitalID = HospitalID } : DB.BingQus.Where(v => v.ID == ID).FirstOrDefault();
            return PartialView("EditBingQu", m);
        }

        [HttpPost]
        public ActionResult EditBingQu(BingQu m)
        {
            if (string.IsNullOrEmpty(m.ID))
            {
                m.ID = DB.NewID();
                DB.BingQus.AddObject(m);
            }
            else
            {
                var om = DB.BingQus.First(v => v.ID == m.ID);
                DB.BingQus.ApplyCurrentValues(m);
            }
            DB.SaveChanges();

            return RedirectToAction("Hospitals", new { hid = m.HospitalID, bid = m.ID });
        }
        [HttpGet]
        public ActionResult DelBingQu(string ID)
        {
            var m = DB.BingQus.Where(v => v.ID == ID).SingleOrDefault();
            DB.DeleteObject(m);
            DB.SaveChanges();
            //return RedirectToAction("Departments");
            return RedirectToAction("Hospitals", new { hid = m.HospitalID });

        }


        [HttpGet]
        public ActionResult EditDepartment(string ID, string BingQuID)
        {
            Department m = null;
            if (string.IsNullOrEmpty(ID))
            {
                var b = DB.BingQus.First(v => v.ID == BingQuID);
                m = new Department() { HospitalID = b.HospitalID, BingQuID = b.ID };
            }
            else
            {
                m = DB.Departments.Where(v => v.DepartmentID == ID).FirstOrDefault();
            }
            return PartialView("DepartmentItem", m);
        }
        [HttpPost]
        public ActionResult EditDepartment(Models.Department m)
        {
            if (ModelState.IsValid)
            {
                if (string.IsNullOrEmpty(m.DepartmentID))
                {
                    m.DepartmentID = DB.NewID();
                    DB.Departments.AddObject(m);
                }
                else
                {
                    DB.Departments.FirstOrDefault(v => v.DepartmentID == m.DepartmentID);
                    DB.Departments.ApplyCurrentValues(m);
                }

                DB.SaveChanges();
                //return RedirectToAction("Departments", new { HospitalID = m.HospitalID });
                return RedirectToAction("Hospitals", new { hid = m.HospitalID, bid = m.BingQuID, did = m.DepartmentID });
            }
            else
            {
                throw new ArgumentException("输入不正确。");
            }

        }


        [HttpGet]
        public ActionResult DelDepartment(string ID)
        {
            var m = DB.Departments.Where(v => v.DepartmentID == ID).SingleOrDefault();
            DB.DeleteObject(m);
            DB.SaveChanges();
            //return RedirectToAction("Departments");
            return RedirectToAction("Hospitals", new { hid = m.HospitalID, bid = m.BingQuID });
        }



        /////////////////////Enum

        [HttpGet]
        public ActionResult EnumMgr()
        {
            return View();
        }

        [HttpGet]
        public ActionResult EnumList()
        {
            return PartialView(DB.EnumDefine_NoSys);
        }

        [HttpGet]
        public ActionResult EnumItem(string ID)
        {
            return PartialView(DB.EnumDefines.Where(v => v.EnumID == ID).FirstOrDefault());
        }


        [HttpGet]
        public ActionResult EnumEdit()
        {

            return PartialView();
        }

        [HttpPost]
        public ActionResult EnumEdit(EnumDefine m)
        {
            if (ModelState.IsValid)
            {
                m.EnumID = DB.NewID();
                DB.EnumDefines.AddObject(m);

                string[] keys = Request.Form.GetValues("NewValueKey");
                string[] texts = Request.Form.GetValues("NewValueText");
                string[] SF36s = Request.Form.GetValues("NewSF36Value");


                for (int i = 0; i < keys.Length; i++)
                {
                    if (!string.IsNullOrWhiteSpace(keys[i]) && !string.IsNullOrWhiteSpace(texts[i]))
                    {
                        DB.EnumValues.AddObject(new EnumValue() { EnumValID = DB.NewID(), EnumID = m.EnumID, OptionValue = keys[i].Trim(), OptionTitle = texts[i].Trim(), SF36Value = Math.Round(double.Parse(SF36s[i].Trim()), 1) });
                    }
                }

                DB.SaveChanges();

                //return RedirectToAction("EnumItem", new { ID=m.EnumID});
                return RedirectToAction("EnumList"); //return PartialView("EnumItem", m);
            }
            else
            {
                throw new ArgumentException("输入不正确。");
            }
        }

        [HttpGet]
        public ActionResult EditEnum(string ID)
        {
            var m = DB.EnumDefines.Where(v => v.EnumID == ID).FirstOrDefault();
            return PartialView("EnumEdit", m);
        }
        [HttpPost]
        public ActionResult EditEnum(Models.EnumDefine m)
        {

            if (ModelState.IsValid)
            {
                var om = DB.EnumDefines.Where(v => v.EnumID == m.EnumID).FirstOrDefault();
                string[] okeys = Request.Form.GetValues("item.OptionValue");
                string[] otexts = Request.Form.GetValues("item.OptionTitle");
                string[] oids = Request.Form.GetValues("item.EnumValID");
                string[] oSF36s = Request.Form.GetValues("item.SF36Value");

                if (null != oids && oids.Length > 0)
                {
                    for (int i = 0; i < oids.Length; i++)
                    {
                        var ev = om.EnumValues.Where(v => v.EnumValID == oids[i]).FirstOrDefault();
                        if (ev == null) continue;
                        if (string.IsNullOrWhiteSpace(okeys[i]))
                        {
                            om.EnumValues.Remove(ev);
                            DB.EnumValues.DeleteObject(ev);
                        }
                        else
                        {
                            if (ev.OptionValue != okeys[i]) ev.OptionValue = okeys[i];
                            if (ev.OptionTitle != otexts[i]) ev.OptionTitle = otexts[i];
                            double sf36v = 0;
                            if (double.TryParse(oSF36s[i], out sf36v))
                            {
                                if (ev.SF36Value != sf36v) ev.SF36Value = sf36v;
                            }
                        }

                    }
                }
                DB.EnumDefines.ApplyCurrentValues(m);



                string[] keys = Request.Form.GetValues("NewValueKey");
                string[] texts = Request.Form.GetValues("NewValueText");
                string[] SF36s = Request.Form.GetValues("NewSF36Value");

                for (int i = 0; i < keys.Length; i++)
                {
                    if (!string.IsNullOrWhiteSpace(keys[i]) && !string.IsNullOrWhiteSpace(texts[i]))
                    {
                        double sf36v = 0;
                        double.TryParse(oSF36s[i], out sf36v);
                        DB.EnumValues.AddObject(new EnumValue() { EnumValID = DB.NewID(), EnumID = m.EnumID, OptionValue = keys[i].Trim(), OptionTitle = texts[i].Trim(), SF36Value = sf36v });
                    }
                }

                DB.SaveChanges();
                return RedirectToAction("EnumList"); //return PartialView("EnumItem", om);
            }
            else
            {
                throw new ArgumentException("输入不正确。");
            }

        }
        [HttpGet]
        public ActionResult DelEnum(string ID)
        {
            var m = DB.EnumDefines.Where(v => v.EnumID == ID).FirstOrDefault();
            if (m.QizItems.Count > 0)
            {
                throw new SiteException("指定的内容已经在使用中,不能删除。");
            }



            foreach (var ev in m.EnumValues.ToList()) DB.DeleteObject(ev);
            DB.DeleteObject(m);

            DB.SaveChanges();
            return RedirectToAction("EnumList");

        }



        /////////////////////SuiFang

        [HttpGet]
        public ActionResult SuiFangMgr()
        {
            return View();
        }

        [HttpGet]
        public ActionResult SuiFangTree(string ID, string cids)
        {
            if (null != cids) ViewBag.cids = cids.Split(',');
            if (string.IsNullOrEmpty(ID)) return PartialView(DB.Catalogs.Where(v => (v.ParentCatalogID == "0" && v.RootFlag == "SuiFang")).FirstOrDefault());
            else return PartialView(DB.Catalogs.Where(v => v.CatalogID == ID).First());
        }



        [HttpGet]
        public ActionResult SuiFangForm(string ID, string itemID)
        {
            ViewBag.SuiFangID = ID;
            ViewBag.ItemID = itemID;
            ViewBag.Types = DB.EnumValues.Where(v => v.EnumID == "01002").ToList();
            return PartialView(DB.Catalogs.Where(v => v.CatalogID == ID).First());
        }
        //[HttpGet]
        //public ActionResult SuiFangForm(string ID,string itemID)
        //{
        //    ViewBag.SuiFangID = ID;
        //    ViewBag.Types = DB.EnumValues.Where(v => v.EnumID == "01002").ToList();
        //    ViewBag.ItemID = itemID;
        //    return PartialView(DB.Catalogs.Where(v => v.CatalogID == ID).First());
        //}
        [HttpPost]
        public ActionResult CreateSuiFangForm(string TreeID, string NewName, string Submit)
        {
            var m = DB.Catalogs.First(v => v.CatalogID == TreeID);
            if (Submit == "改名")
            {
                if (!string.IsNullOrWhiteSpace(NewName))
                {
                    m.Title = NewName;
                    //DB.Catalogs.AddObject(new Models.Catalog() { ParentCatalogID = TreeID, CatalogID = DB.NewID(), Title = NewName });
                    DB.SaveChanges();
                }
            }
            else if (Submit == "添加")
            {
                if (!string.IsNullOrWhiteSpace(NewName))
                {
                    DB.Catalogs.AddObject(new Models.Catalog() { ParentCatalogID = TreeID, CatalogID = DB.NewID(), Title = NewName });
                    DB.SaveChanges();
                }
            }
            //if (!string.IsNullOrWhiteSpace(NewName))
            //{
            //    DB.Catalogs.AddObject(new Models.Catalog() { ParentCatalogID = TreeID, CatalogID = DB.NewID(), Title = NewName });
            //    DB.SaveChanges();
            //}
            //return RedirectToAction("SuiFangTree", new { ID = TreeID });
            List<string> cids = new List<string>();
            cids.Add(m.CatalogID);
            while (m.ParentCatalogID != "0")
            {
                cids.Add(m.CatalogID);
                m = m.ParentCatalog;
            }
            return RedirectToAction("SuiFangTree", new { ID = string.Empty, cids = string.Join(",", cids.ToArray()) });
            //return View();
        }
        [HttpPost]
        public ActionResult DelSuiFangForm(string ID)
        {
            var m = DB.Catalogs.Where(v => v.CatalogID == ID).First();
            if (!string.IsNullOrEmpty(m.RootFlag)) throw new ArgumentException("关键节点不允许删除。");
            DB.Catalogs.DeleteObject(m);
            //delete sub catas
            //delete sub items;
            DB.SaveChanges();
            return RedirectToAction("SuiFangForm", new { ID = m.ParentCatalogID, itemID = string.Empty });
            //return PartialView();
        }




        [HttpGet]
        public ActionResult SuiFangItem(string ID, string SuiFangID)
        {
            ViewBag.Departments = DB.Departments;
            ViewBag.EnumDefines = DB.EnumDefine_NoSys;

            ViewBag.Types = DB.EnumValues.Where(v => v.EnumID == "01002").ToList();

            if (ID == null) return PartialView(new Models.QizItem() { Catalog = DB.Catalogs.Where(v => v.CatalogID == SuiFangID).First() });
            else return PartialView(DB.QizItems.Where(v => v.QizItemID == ID).FirstOrDefault());
        }
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult SuiFangItem(QizItem m)
        {
            if (string.IsNullOrEmpty(m.QizItemID))
            {
                m.QizItemID = DB.NewID();
                DB.QizItems.AddObject(m);
            }
            else
            {
                DB.QizItems.Where(v => v.QizItemID == m.QizItemID).FirstOrDefault();
                DB.QizItems.ApplyCurrentValues(m);
                m = DB.QizItems.Where(v => v.QizItemID == m.QizItemID).FirstOrDefault();
            }

            DB.SaveChanges();
            return RedirectToAction("SuiFangForm", new { ID = m.CatalogID, itemID = m.QizItemID });
        }


        [HttpGet]
        public ActionResult SuiFangItemToDep(string ID)
        {
            var qi = DB.QizItems.FirstOrDefault(v => v.QizItemID == ID);
            ViewBag.QizItemID = qi.QizItemID;
            ViewBag.SelDeps = qi.QizItemToDeps.Select(v => v.DepID);

            var m = DB.Hospitals;
            return PartialView(m);
        }

        [HttpPost]
        public ActionResult SuiFangItemToDep(string ID, string[] DepIDs)
        {
            if (DepIDs == null) DepIDs = new string[0];
            var m = DB.QizItems.FirstOrDefault(v => v.QizItemID == ID);
            if (null == m) throw new ArgumentException("内容不存在。");
            var oriDepIDs = m.QizItemToDeps.Select(v => v.DepID);

            var toRemove = oriDepIDs.Except(DepIDs);
            var toAddDepIDs = DepIDs.Except(oriDepIDs);

            foreach (var item in m.QizItemToDeps.Where(v => toRemove.Contains(v.DepID)).ToList())
            {
                DB.QizItemToDeps.DeleteObject(item);
            }
            foreach (var item in toAddDepIDs)
            {
                DB.QizItemToDeps.AddObject(new QizItemToDep() { ID = DB.NewID(), QizItemID = ID, DepID = item });
            }
            DB.SaveChanges();
            return RedirectToAction("SuiFangForm", new { ID = m.CatalogID, itemID = m.QizItemID });
        }


        [HttpGet]
        public ActionResult DelSuiFangItem(string ID)
        {
            var m = DB.QizItems.Where(v => v.QizItemID == ID).FirstOrDefault();
            DB.QizItems.DeleteObject(m);
            DB.SaveChanges();
            return RedirectToAction("SuiFangForm", new { ID = m.CatalogID });
        }

        /////////////////////SuiFangTemplate

        [HttpGet]
        public ActionResult SuiFangTemplateMgr()
        {
            return View();
        }

        [HttpGet]
        public ActionResult SuiFangTemplateTree(string ID)
        {
            if (string.IsNullOrEmpty(ID)) return PartialView(DB.Catalogs.Where(v => (v.ParentCatalogID == "0" && v.RootFlag == "SuiFangTemplate")).FirstOrDefault());
            else return PartialView(DB.Catalogs.Where(v => v.CatalogID == ID).First());
        }

        [HttpPost]
        public ActionResult CreateSuiFangTemplateForm(string TreeID, string NewName)
        {

            DB.Catalogs.AddObject(new Models.Catalog() { ParentCatalogID = TreeID, CatalogID = DB.NewID(), Title = NewName });
            DB.SaveChanges();
            return RedirectToAction("SuiFangTemplateTree", new { ID = TreeID });
            //return View();
        }
        [HttpPost]
        public ActionResult DelSuiFangTemplateForm(string ID)
        {
            var m = DB.Catalogs.Where(v => v.CatalogID == ID).First();
            if (!string.IsNullOrEmpty(m.RootFlag)) throw new ArgumentException("关键节点不允许删除。");
            DB.Catalogs.DeleteObject(m);
            //delete sub catas
            //delete sub items;
            DB.SaveChanges();
            return RedirectToAction("SuiFangTemplateForm", new { ID = m.ParentCatalogID });
            //return PartialView();
        }


        [HttpGet]
        public ActionResult SuiFangTemplateForm(string ID)
        {
            ViewBag.SuiFangTemplateID = ID;

            return PartialView(DB.Catalogs.Where(v => v.CatalogID == ID).First());
        }

        [HttpGet]
        public ActionResult SuiFangTemplateItem(string ID, string SuiFangTemplateID)
        {
            ViewBag.Departments = DB.Departments;
            if (ID == null) return PartialView(new Models.QizTemplate() { Catalog = DB.Catalogs.Where(v => v.CatalogID == SuiFangTemplateID).First() });
            else return PartialView(DB.QizTemplates.Where(v => v.QizFormTemplateID == ID).FirstOrDefault());
        }
        [HttpPost]
        public ActionResult SuiFangTemplateItem(QizTemplate m)
        {
            if (string.IsNullOrEmpty(m.QizFormTemplateID))
            {
                m.QizFormTemplateID = DB.NewID();
                DB.QizTemplates.AddObject(m);
            }
            else
            {
                DB.QizTemplates.Where(v => v.QizFormTemplateID == m.QizFormTemplateID).FirstOrDefault();
                DB.QizTemplates.ApplyCurrentValues(m);
                m = DB.QizTemplates.Where(v => v.QizFormTemplateID == m.QizFormTemplateID).FirstOrDefault();
            }

            DB.SaveChanges();
            return RedirectToAction("SuiFangTemplateForm", new { ID = m.CatalogID });
        }
        [HttpGet]
        public ActionResult DelSuiFangTemplateItem(string ID)
        {
            var m = DB.QizTemplates.Where(v => v.QizFormTemplateID == ID).FirstOrDefault();
            DB.QizTemplates.DeleteObject(m);
            DB.SaveChanges();
            return RedirectToAction("SuiFangTemplateForm", new { ID = m.CatalogID });
        }

        ////////////////////////////////////////////////MingXi


        //[HttpGet]
        //public ActionResult SftMingXiMgr(string ID)
        //{
        //    var m = DB.QizTemplates.Where(v => v.QizFormTemplateID == ID).FirstOrDefault();
        //    return PartialView(m);
        //}
        //[HttpGet]
        //public ActionResult SftMingXiList(string ID)
        //{
        //    var m = DB.QizTemplates.Where(v => v.QizFormTemplateID == ID).FirstOrDefault();
        //    return PartialView(m);
        //}

        //[HttpGet]
        //public ActionResult SftMingXiAdd(string ID) {
        //    var om = DB.QizTemplates.Where(v => v.QizFormTemplateID == ID).FirstOrDefault();
        //    var qis=from v in om.QizTemplateDefines
        //            select v.QizItemID;

        //    var m = DB.QizItems.Where(v => ! qis.Contains(v.QizItemID));
        //    ViewBag.ID = ID;
        //    return PartialView(m);
        //}

        //[HttpPost]
        //public ActionResult SftMingXiAdd(string ID,string[] Selection)
        //{
        //    var om = DB.QizTemplates.Where(v => v.QizFormTemplateID == ID).FirstOrDefault();

        //    var ms = om.QizTemplateDefines.Count > 0 ? om.QizTemplateDefines.Max(v => v.SortIdx) : 0;

        //    var m = DB.QizItems.Where(v => Selection.Contains(v.QizItemID));

        //    foreach (var v in m)
        //    {
        //        var nm=new QizTemplateDefine(){ QizItemID=v.QizItemID,QizTemplateID=ID,SortIdx=ms++, QizTempDefID=DB.NewID()};
        //        om.QizTemplateDefines.Add(nm);
        //    }
        //    DB.SaveChanges();
        //    return RedirectToAction("SftMingXiList", new { ID = ID });
        //}

        //[HttpGet]
        //public ActionResult SortSftMingXi(string ID,string Sort)
        //{
        //    var m = DB.QizTemplateDefines.Where(v => v.QizTempDefID == ID).FirstOrDefault();

        //    var om = DB.QizTemplateDefines.Where(v => v.QizTemplateID == m.QizTemplateID && v.SortIdx == m.SortIdx + (Sort == "U" ? -1 : 1)).FirstOrDefault();

        //    if (null != om)
        //    {
        //        var t = m.SortIdx; m.SortIdx = om.SortIdx; om.SortIdx = t;
        //    }
        //    else {
        //        //m.SortIdx = m.SortIdx + (Sort == "U" ? -1 : 1);
        //    }
        //    DB.SaveChanges();

        //    return RedirectToAction("SftMingXiList", new { ID = m.QizTemplateID });
        //}
        //[HttpGet]
        //public ActionResult DelSftMingXi(string ID)
        //{
        //    var m = DB.QizTemplateDefines.Where(v => v.QizTempDefID == ID).FirstOrDefault();
        //    DB.QizTemplateDefines.DeleteObject(m);

        //    foreach (var item in DB.QizTemplateDefines.Where(v=>v.QizTemplateID==m.QizTemplateID && v.SortIdx>m.SortIdx))
        //    {
        //        item.SortIdx = item.SortIdx - 1;
        //    }
        //    DB.SaveChanges();
        //    return RedirectToAction("SftMingXiList", new { ID = m.QizTemplateID});
        //}

        /////////////////////quiz subject////////////////////
        //public ActionResult QuizSubjectDetail(string ID) {
        //    var m = DB.QizSubjects.Where(v => v.ID == ID).First();
        //    return PartialView(m);
        //}

        /////////////////////////////////Ming xi



        //[HttpGet]
        //public ActionResult SftMingXiMgr(string ID)
        //{
        //    var m = DB.QizSubjects;
        //    ViewBag.QizSubjectID = ID;
        //    return View(m);
        //}
        [HttpGet]
        public ActionResult SftMingXiEdit(string ID)
        {
            string[] svs = { "4", "5" };
            var m = DB.QizSubjectDefines.Where(v => v.ID == ID).FirstOrDefault();
            ViewBag.Selections = m.QizSubject.QizSubjectDefines.Where(v => v.ID != ID && svs.Contains(v.QizItem.TypeRef.OptionValue));

            return PartialView(m);
        }

        [HttpPost]
        public ActionResult SftMingXiEdit(QizSubjectDefine tm, string[] MulitSeletion)
        {
            var m = DB.QizSubjectDefines.Where(v => v.ID == tm.ID).FirstOrDefault();
            if (m.QizItem.Type != "207")
            {
                //if (string.IsNullOrEmpty(m.ThresholdLow)) m.ThresholdLow = null;
                //else
                //{

                if (m.QizItem.TypeRef.OptionValue == "2")
                {
                    m.ThresholdLow = tm.ThresholdLow;
                }
                else
                {
                    m.ThresholdLow = MulitSeletion == null ? null : string.Join(",", MulitSeletion);
                }
                //}
                m.ThresholdHight = tm.ThresholdHight;
                m.YiChangTiXing = tm.YiChangTiXing;

                m.ParentSubjDefID = string.IsNullOrEmpty(tm.ParentSubjDefID) ? null : tm.ParentSubjDefID;
                if (null != m.ParentSubjDefID)
                {
                    m.ParentSubjDefVals = tm.ParentSubjDefVals == null ? null : string.Join(",", tm.ParentSubjDefVals);
                    if (m.ParentSubjDefVals == null)
                    {
                        throw new SiteException("必须选择正确的选择项。");
                    }
                }
            }
            m.IsAllowInMobile = tm.IsAllowInMobile;
            m.ShortTitle = tm.ShortTitle;

            DB.SaveChanges();
            return RedirectToAction("SftMingXiList", new { ID = m.QizSubjectID });
        }

        [HttpGet]
        public ActionResult SftMingXiList(string ID)
        {
            var m = DB.QizSubjects.Where(v => v.ID == ID).FirstOrDefault();
            return PartialView(m);
        }

        [HttpGet]
        public ActionResult SftMingXiAdd(string ID)
        {
            var om = DB.QizSubjects.Where(v => v.ID == ID).FirstOrDefault();
            var qis = from v in om.QizSubjectDefines
                      select v.QizItemID;

            //var m = om.Department.QizItemToDeps.Select(v=>v.QizItem).Where(v => !qis.Contains(v.QizItemID));
            ViewBag.ID = ID;
            ViewBag.DepID = om.DepID;
            ViewBag.QIDS = qis.ToArray();
            var m = DB.Catalogs.FirstOrDefault(v => (v.ParentCatalogID == "0" && v.RootFlag == "SuiFang"));


            return PartialView(m);
        }

        [HttpGet]
        public ActionResult SftMingXiEnumTypeValus(string ID, string srcID)
        {
            if (!string.IsNullOrEmpty(srcID)) ViewBag.SrcQSD = DB.QizSubjectDefines.Where(v => v.ID == srcID).FirstOrDefault();
            var m = DB.QizSubjectDefines.Where(v => v.ID == ID).FirstOrDefault();
            return PartialView(m);
        }
        [HttpGet]
        public ActionResult SftMingXiZhenDuan(string ID)
        {
            var m = DB.QizSubjectDefines.Where(v => v.ID == ID).FirstOrDefault();
            return PartialView(m);
        }
        [HttpPost]
        public ActionResult SftMingXiZhenDuan(string ID, string Low, string High, string YiChangTiXing, string[] MulitSeletion)
        {
            if (MulitSeletion != null)
            {
                var m = DB.QizSubjectDefines.Where(v => v.ID == ID).FirstOrDefault();
                m.ThresholdLow = string.Empty;
                foreach (var s in MulitSeletion)
                {
                    m.ThresholdLow += s + ",";
                }
                m.ThresholdLow = m.ThresholdLow.TrimEnd(',');
                m.YiChangTiXing = string.IsNullOrWhiteSpace(YiChangTiXing) ? null : YiChangTiXing;
                DB.SaveChanges();
                return Content("操作完成");
            }
            else
            {
                var m = DB.QizSubjectDefines.Where(v => v.ID == ID).FirstOrDefault();
                m.ThresholdLow = string.IsNullOrEmpty(Low) ? null : Low;
                m.ThresholdHight = string.IsNullOrEmpty(High) ? null : High;
                m.YiChangTiXing = string.IsNullOrWhiteSpace(YiChangTiXing) ? null : YiChangTiXing;
                DB.SaveChanges();
                return Content("操作完成");
            }

        }

        [HttpGet]
        public ActionResult SftMingXiRelation(string ID)
        {
            string[] svs = { "4", "5" };
            var m = DB.QizSubjectDefines.Where(v => v.ID == ID).FirstOrDefault();
            ViewBag.Selections = m.QizSubject.QizSubjectDefines.Where(v => v.ID != ID && svs.Contains(v.QizItem.TypeRef.OptionValue));
            return PartialView(m);
        }

        [HttpPost]
        public ActionResult SftMingXiRelation(string ID, string ParentSubjDefID, string[] ParentSubjDefVals)
        {

            var m = DB.QizSubjectDefines.Where(v => v.ID == ID).FirstOrDefault();
            m.ParentSubjDefID = string.IsNullOrEmpty(ParentSubjDefID) ? null : ParentSubjDefID;
            m.ParentSubjDefVals = ParentSubjDefVals == null ? null : string.Join(",", ParentSubjDefVals);
            if (m.ParentSubjDefVals == null)
            {
                throw new SiteException("必须选择正确的选择项。");
            }
            DB.SaveChanges();
            return RedirectToAction("SftMingXiList", new { ID = m.QizSubjectID });

        }

        [HttpPost]
        public ActionResult SftMingXiAdd(string ID, string[] Selection)
        {
            if (null != Selection)
            {
                var om = DB.QizSubjects.Where(v => v.ID == ID).FirstOrDefault();

                var ms = om.QizSubjectDefines.Count > 0 ? om.QizSubjectDefines.Max(v => v.SortIdx) : 0;

                var m = DB.QizItems.Where(v => Selection.Contains(v.QizItemID));

                foreach (var v in m)
                {
                    var nm = new QizSubjectDefine() { QizItemID = v.QizItemID, QizSubjectID = ID, SortIdx = ++ms, ID = DB.NewID() };
                    om.QizSubjectDefines.Add(nm);
                }
                DB.SaveChanges();
            }
            return RedirectToAction("SftMingXiList", new { ID = ID });
        }

        [HttpGet]
        public ActionResult SortSftMingXi(string ID, string Sort)
        {
            var m = DB.QizSubjectDefines.Where(v => v.ID == ID).FirstOrDefault();

            var om = DB.QizSubjectDefines.Where(v => v.QizSubjectID == m.QizSubjectID && v.SortIdx == m.SortIdx + (Sort == "U" ? -1 : 1)).FirstOrDefault();

            if (null != om)
            {
                var t = m.SortIdx; m.SortIdx = om.SortIdx; om.SortIdx = t;
            }
            else
            {
                //m.SortIdx = m.SortIdx + (Sort == "U" ? -1 : 1);
            }
            DB.SaveChanges();

            return RedirectToAction("SftMingXiList", new { ID = m.QizSubjectID });
        }
        public ActionResult SortSftMingXiVal(string ID, int srcidx, int desidx)
        {
            var m = DB.QizSubjectDefines.Where(v => v.QizSubjectID == ID && v.SortIdx == srcidx).FirstOrDefault();
            var nm = DB.QizSubjectDefines.Where(v => v.QizSubjectID == m.QizSubjectID && v.SortIdx == m.SortIdx).FirstOrDefault();


            if (null != m && null != nm)
            {
                if (srcidx > desidx)
                {
                    DB.ExecuteStoreCommand("Update QizSubjectDefine Set SortIdx=SortIdx+1 Where QizSubjectID={0} And SortIdx>={1} And SortIdx<{2} ", ID, desidx, srcidx);
                    m.SortIdx = desidx;
                }
                else if (srcidx < desidx)
                {
                    DB.ExecuteStoreCommand("Update QizSubjectDefine Set SortIdx=SortIdx-1 Where QizSubjectID={0} And SortIdx<={1} And SortIdx>{2} ", ID, desidx, srcidx);
                    m.SortIdx = desidx;
                }

            }
            else
            {
                throw new SiteException("请输入正确的源和目标序号。");
            }
            DB.SaveChanges();

            return RedirectToAction("SftMingXiList", new { ID = ID });
        }
        [HttpGet]
        public ActionResult DelSftMingXi(string ID)
        {
            var m = DB.QizSubjectDefines.Where(v => v.ID == ID).FirstOrDefault();
            DB.QizSubjectDefines.DeleteObject(m);

            foreach (var item in DB.QizSubjectDefines.Where(v => v.QizSubjectID == m.QizSubjectID && v.SortIdx > m.SortIdx))
            {
                item.SortIdx = item.SortIdx - 1;
            }
            DB.SaveChanges();
            return RedirectToAction("SftMingXiList", new { ID = m.QizSubjectID });
        }

        /////////////////////随访单

        //
        // GET: /SystemMgr/
        public ActionResult SuiFangDanMgr()
        {

            return View();
        }

        public ActionResult SFDList()
        {
            var m = DB.QizSubjects;
            return PartialView(m);
        }

        public ActionResult AdminEdit()
        {
            //if (ID == Guid.Empty) return PartialView(new aspnet_Users());
            //else 
            return PartialView(DB.aspnet_Users.Where(v => v.UserId == SiteUser.UserId).FirstOrDefault());
        }
        [HttpPost]
        public ActionResult AdminEdit(aspnet_Users m, string Pwd)
        {
            if (!string.IsNullOrEmpty(Pwd))
            {
                var mu = Membership.GetUser(m.UserName);
                mu.ChangePassword(mu.ResetPassword(), Pwd);
            }
            //var tm = m;
            var tm = DB.aspnet_Users.Where(v => v.UserId == m.UserId).FirstOrDefault();
            tm.MobileAlias = m.MobileAlias;
            DB.SaveChanges();
            return RedirectToAction("DrList");
        }

        [HttpPost]
        public ActionResult SFDList(string Search)
        {
            if (string.IsNullOrWhiteSpace(Search))
            {
                var m = DB.QizSubjects;
                return PartialView(m);
            }
            else
            {
                IQueryable<QizSubject> m = null;
                DateTime dt = DateTime.MinValue;
                if (DateTime.TryParse(Search, out dt))
                {
                    m = DB.QizSubjects.Where(v => (v.CreateTime > dt.AddMonths(-1) && v.CreateTime < dt.AddMonths(1)));
                }
                else
                {
                    m = DB.QizSubjects.Where(v =>
                        v.ID.Contains(Search) ||
                        v.Title.Contains(Search) ||
                        v.Department.DepName.Contains(Search) ||
                        v.Owner.UserName.Contains(Search) ||
                        v.Creator.UserName.Contains(Search) ||
                        v.StatusRef.OptionTitle.Contains(Search) ||
                        v.Tag.Contains(Search));
                }
                return PartialView(m);
            }
        }
        [HttpGet]
        public ActionResult SFDEdit(string ID, string DepID)
        {
            //ViewBag.Templates = DB.QizTemplates;
            var d = DB.Departments.Where(v => v.DepartmentID == DepID).FirstOrDefault();
            if (string.IsNullOrEmpty(ID))
            {
                ViewBag.ParentSubject = DB.QizSubjects.Where(s => s.Department.DepartmentID == d.DepartmentID && (s.SubjectType == null || s.SubjectType == "常规随访单"));
                return PartialView(new QizSubject() { DepID = d.DepartmentID, HospID = d.HospitalID, CreatorID = SiteUser.UserId, OwnerID = SiteUser.UserId });
            }
            else
            {
                var sub = DB.QizSubjects.Where(v => v.ID == ID).FirstOrDefault();
                ViewBag.ParentSubject = DB.QizSubjects.Where(s => s.Department.DepartmentID == sub.Department.DepartmentID
                    && (s.SubjectType == null || s.SubjectType == "常规随访单")
                    && s.ID != sub.ID);
                return PartialView(sub);
            }
        }
        [HttpPost]
        public ActionResult SFDEdit(QizSubject m, bool IsInitFromTemplate = false, string QizTemplateID = "")
        {
            //if (ModelState.IsValid)
            //{
            if (string.IsNullOrEmpty(m.ID))
            {
                m.ID = DB.NewID();
                DB.QizSubjects.AddObject(m);
            }
            else
            {
                DB.QizSubjects.Where(v => v.ID == m.ID).First();
                DB.QizSubjects.ApplyCurrentValues(m);
                m = DB.QizSubjects.Where(v => v.ID == m.ID).First();
            }
            DB.SaveChanges();
            m = DB.QizSubjects.First(v => v.ID == m.ID);

            //return RedirectToAction("SFDList");
            return RedirectToAction("Hospitals", new { hid = m.HospID, bid = m.Department.BingQuID, did = m.DepID, sid = m.ID });
            //}
            //else
            //{
            //    throw new ArgumentException("输入不正确。");
            //}
        }

        public ActionResult SFDDelete(string ID)
        {
            var m = DB.QizSubjects.Where(v => v.ID == ID).FirstOrDefault();
            DB.QizSubjects.DeleteObject(m);
            DB.SaveChanges();
            //return RedirectToAction("SFDList");
            return RedirectToAction("Hospitals", new { hid = m.HospID, did = m.DepID, sid = m.ID });
        }
        public ActionResult SFDView(string ID)
        {
            return View(DB.QizSubjects.Where(v => v.ID == ID).FirstOrDefault());
        }
        //////////////////////NewSF36
        public ActionResult NewSF36(string DepID)
        {
            //public ActionResult SFDEdit(QizSubject m, bool IsInitFromTemplate = false, string QizTemplateID = "")
            var sf36t = DB.QizSubjects.First(v => v.ID == "10001");
            var dep = DB.Departments.First(v => v.DepartmentID == DepID);


            QizSubject m = DB.QizSubjects.FirstOrDefault(v => v.DepID == dep.DepartmentID && v.IsSF36Subject);
            if (null == m)
            {
                m = new QizSubject()
                {
                    IsSF36Subject = true,
                    CreateTime = DateTime.Now,
                    ID = DB.NewID(),
                    Tag = "SF36",
                    Title = "SF-36生活质量调查问卷",
                    CreatorID = SiteUser.UserId,
                    DepID = dep.DepartmentID,
                    HospID = dep.BingQu.HospitalID,
                    StatusID = "100"
                };
                DB.QizSubjects.AddObject(m);

                foreach (var item in sf36t.QizSubjectDefines.ToList())
                {
                    DB.Detach(item);
                    item.ID = DB.NewID();
                    item.QizSubjectID = m.ID;
                    m.QizSubjectDefines.Add(item);
                }
                DB.SaveChanges();
            }
            //return RedirectToAction("Hospitals", new { hid = m.HospID, did = m.DepID, sid = m.ID });
            return Content("<h3>操作完成，但是此特殊功能，需要手动刷新页面才能更新左侧列表。</h3>");
        }

        //
        // GET: /SystemMgr/
        public ActionResult DoctorMgr()
        {
            return View();
        }


        public ActionResult DrList()
        {
            ViewBag.Departments = DB.Departments.Select(s => s.DepName).Distinct();
            ViewBag.Hospitals = DB.Hospitals_Fixed;
            ViewBag.Binqus = DB.BingQus.Select(s => s.Title).Distinct();
            //var m = DB.aspnet_Roles.Where(v => v.RoleName == "Doctor").First().aspnet_Users;
            //ViewBag.Departments = DB.Departments;
            //ViewBag.Hospitals = DB.Hospitals_Fixed;
            //return PartialView(m);
            return DrList(null);
        }
        [HttpPost]
        public ActionResult DrList(ListViewModel<CommonSearchValues, IQueryable<aspnet_Users>> m)
        {
            ViewBag.Departments = DB.Departments.Select(s => s.DepName).Distinct();
            ViewBag.Hospitals = DB.Hospitals_Fixed;
            ViewBag.Binqus = DB.BingQus.Select(s => s.Title).Distinct();
            if (null == m || null == m.SearchFrom)
            {
                m = new ListViewModel<CommonSearchValues, IQueryable<aspnet_Users>>()
                {
                    PageIdx = 0,
                    PageSize = 0,
                    SearchFrom = new CommonSearchValues { V3 = string.Empty, V1 = string.Empty, V2 = string.Empty },
                    SearchTo = new CommonSearchValues { V3 = string.Empty }
                };
            }
            IQueryable<aspnet_Users> d = DB.Doctors.AsQueryable();
            if (null != m.SearchFrom)
            {
                if (!string.IsNullOrWhiteSpace(m.SearchFrom.V1)) { d = d.Where(v => v.UserName == m.SearchFrom.V1); }
                if (!string.IsNullOrWhiteSpace(m.SearchFrom.V2)) { d = d.Where(v => v.MobileAlias == m.SearchFrom.V2); }
                if (!string.IsNullOrWhiteSpace(m.SearchFrom.V3)) { d = d.Where(v => v.HospitalID == m.SearchFrom.V3); }
                if (!string.IsNullOrWhiteSpace(m.SearchFrom.V4)) { d = d.Where(v => v.Department != null && v.Department.DepName == m.SearchFrom.V4); }
                if (!string.IsNullOrWhiteSpace(m.SearchFrom.V5)) { d = d.Where(v => v.BingQu != null && v.BingQu.Title == m.SearchFrom.V5); }
                if (!string.IsNullOrWhiteSpace(m.SearchFrom.V6)) { d = d.Where(v => v.AccountStatus == m.SearchFrom.V6); }
            }

            m.Data = d;
            return PartialView(m);
        }

        public ActionResult DrEdit(Guid ID)
        {
            ViewBag.Departments = DB.Departments;
            ViewBag.Hospitals = DB.Hospitals_Fixed;

            if (ID == Guid.Empty) return PartialView(new aspnet_Users());
            else return PartialView(DB.aspnet_Users.Where(v => v.UserId == ID).FirstOrDefault());
        }
        [HttpPost]
        public ActionResult DrEdit(aspnet_Users m, string Pwd)
        {
            var tm = m;
            var isnew = m.UserId == Guid.Empty;
            MembershipUser mu = null;
            if (isnew)
            {
                mu = Membership.CreateUser(m.UserName, Pwd);
                if (null == mu)
                {

                    ModelState.AddModelError("", new Exception("Error when create user."));
                    return PartialView(m);
                }
                System.Web.Security.Roles.AddUserToRole(mu.UserName, "Doctor");
                tm = DB.aspnet_Users.Where(v => v.UserName == m.UserName).FirstOrDefault();
            }
            else
            {
                tm = DB.aspnet_Users.Where(v => v.UserId == m.UserId).FirstOrDefault();
                mu = Membership.GetUser(tm.UserName.ToLower());
            }

            if (!isnew && !string.IsNullOrEmpty(Pwd))
            {
                mu.ChangePassword(mu.ResetPassword(), Pwd);
            }

            if (tm.UserName != m.UserName)
            {
                tm.UserName = m.UserName;
                tm.LoweredUserName = m.UserName.ToLower();
            }

            tm.Gender = m.Gender;
            tm.MainRoleName = "Doctor";
            tm.DepartmentID = m.DepartmentID;
            tm.Department = DB.Departments.First(v => v.DepartmentID == tm.DepartmentID);
            tm.BingQuID = tm.Department.BingQuID;
            tm.HospitalID = tm.Department.HospitalID;
            tm.Email = m.Email;
            tm.AccountStatus = m.AccountStatus;
            tm.MobileAlias = m.MobileAlias;
            tm.IsDoctorDepManager = m.IsDoctorDepManager;
            DB.SaveChanges();
            return RedirectToAction("DrList");
        }

        public ActionResult DrDelete(Guid ID)
        {
            var m = DB.aspnet_Users.Where(v => v.UserId == ID).FirstOrDefault();
            Membership.DeleteUser(m.UserName);
            return RedirectToAction("DrList");
        }
        //////////////////////随访单


        [HttpGet]
        public ActionResult QizSessionList()
        {
            ViewBag.Recupers = DB.Recupers.Select(v => v.User).Distinct();
            ViewBag.Subjects = DB.QizSubjects;
            return PartialView(Services.QizSessionList(null));
        }

        [HttpPost]
        public ActionResult QizSessionList(ListViewModel<CommonSearchValues, IQueryable<QizSession>> m)
        {
            var str = Request["ID"];
            ViewBag.Recupers = DB.Recupers.Select(v => v.User).Distinct();
            ViewBag.Subjects = DB.QizSubjects;
            return PartialView(Services.QizSessionList(m));
        }


        [HttpGet]
        public ActionResult QizSessionMgr()
        {
            return View();
        }

        /////系统短信查询
        public ActionResult ManageSmsList(ListViewModel<CommonSearchValues, IQueryable<SmsSent>> m = null, bool IsView = true)
        {
            if (null == m || m.SearchFrom == null)
            {
                m = new ListViewModel<CommonSearchValues, IQueryable<SmsSent>>()
                {
                    PageSize = Services.DefaultPageSize,
                    SearchFrom = new CommonSearchValues(),
                    SearchTo = new CommonSearchValues()
                };
            }
            var d = DB.SmsSents.AsQueryable();

            if (!string.IsNullOrEmpty(m.SearchFrom.V1)) { d = d.Where(v => v.SenderName == m.SearchFrom.V1); }
            if (!string.IsNullOrEmpty(m.SearchFrom.V2)) { d = d.Where(v => v.ReceiverName == m.SearchFrom.V2); }
            if (!string.IsNullOrEmpty(m.SearchFrom.V3)) { d = d.Where(v => v.SmsType == m.SearchFrom.V3); }
            if (!string.IsNullOrEmpty(m.SearchFrom.V5)) { d = d.Where(v => v.TextMessage.Contains(m.SearchFrom.V5)); }

            if (!string.IsNullOrEmpty(m.SearchFrom.V4)) { var w = DateTime.Parse(m.SearchFrom.V4); d = d.Where(v => v.SentTime >= w); }
            if (!string.IsNullOrEmpty(m.SearchTo.V4)) { var w = DateTime.Parse(m.SearchTo.V4); d = d.Where(v => v.SentTime <= w); }
            m.ItemCount = d.Count();
            m.PageCount = (int)Math.Ceiling((double)d.Count() / m.PageSize);
            d = d.OrderByDescending(v => v.SentTime);
            m.Data = d.Skip(m.PageSize * m.PageIdx).Take(m.PageSize);
            return ViewOrPartial(m);
        }
        //public ActionResult SentSms(ListViewModel<CommonSearchValues, IQueryable<SmsSent>> m = null)
        //{
        //    if (null == m || m.SearchFrom == null)
        //    {
        //        m = new ListViewModel<CommonSearchValues, IQueryable<SmsSent>>()
        //        {
        //            PageSize = Services.DefaultPageSize,
        //            SearchFrom = new CommonSearchValues(),
        //            SearchTo = new CommonSearchValues()
        //        };
        //    }
        //    var d = DB.SmsSents.AsQueryable();

        //    //if (User.IsInRole("Admin") || User.IsInRole("Engineer")) { ;}
        //    //else if (User.IsInRole("Doctor")) { var o = SiteUser.UserId.ToString(); d = d.Where(v => v.ReceiverCode == o); }
        //    if (!string.IsNullOrEmpty(m.SearchFrom.V1)) { var w = DateTime.Parse(m.SearchFrom.V1); d = d.Where(v => v.SentTime >= w); }

        //    m.PageCount = (int)Math.Ceiling((double)d.Count() / m.PageSize);
        //    d = d.OrderByDescending(v => v.SentTime);
        //    m.Data = d;
        //    return ViewOrPartial(m);
        //}

        //////////////////////////////短信随访查询

        [HttpGet]
        public ActionResult QizSmsSessionList()
        {
            ViewBag.Recupers = DB.Recupers.Select(v => v.User);
            ViewBag.Subjects = DB.QizSmsSubjects;
            return ViewOrPartial(Services.QizSmsSessionListForAdmin(null));
        }

        [HttpPost]
        public ActionResult QizSmsSessionList(ListViewModel<CommonSearchValues, IQueryable<QizSmsSession>> m)
        {
            ViewBag.Recupers = DB.Recupers.Select(v => v.User);
            ViewBag.Subjects = DB.QizSmsSubjects;
            return PartialView(Services.QizSmsSessionListForAdmin(m));
        }

        ///////////////////SMS
        public ActionResult ReceivedSms(ListViewModel<CommonSearchValues, IQueryable<SmsReceived>> m = null)
        {
            if (null == m || m.SearchFrom == null)
            {
                m = new ListViewModel<CommonSearchValues, IQueryable<SmsReceived>>()
                {
                    PageSize = Services.DefaultPageSize
                    ,
                    SearchFrom = new CommonSearchValues()
                    ,
                    SearchTo = new CommonSearchValues()
                };
            }
            var d = DB.SmsReceiveds.AsQueryable();

            //if (User.IsInRole("Admin") || User.IsInRole("Engineer")) { ;}
            //else if (User.IsInRole("Doctor")) { var o = SiteUser.UserId.ToString(); d = d.Where(v => v.ReceiverCode == o); }
            if (!string.IsNullOrEmpty(m.SearchFrom.V1))
            {
                var w = DateTime.Parse(m.SearchFrom.V1);
                d = d.Where(v => v.SentTime >= w);
            }

            if (!string.IsNullOrEmpty(m.SearchTo.V1)) { var w = DateTime.Parse(m.SearchTo.V1); d = d.Where(v => v.SentTime <= w); }
            if (!string.IsNullOrEmpty(m.SearchFrom.V2))
            {
                var user = DB.aspnet_Users.FirstOrDefault(u => u.UserName == m.SearchFrom.V2);
                d = d.Where(v => v.SenderCode == user.MobileAlias || v.SenderCode == "86" + user.MobileAlias);
            }
            if (!string.IsNullOrEmpty(m.SearchFrom.V3))
            {
                d = d.Where(v => v.SenderCode == m.SearchFrom.V3 || v.SenderCode == "86" + m.SearchFrom.V3);
            }
            m.ItemCount = d.Count();
            m.PageCount = (int)Math.Ceiling((double)d.Count() / m.PageSize);
            d = d.OrderByDescending(v => v.SentTime);
            m.Data = d.Skip(m.PageSize * m.PageIdx).Take(m.PageSize);

            var mds = m.Data.Select(v => v.SenderCode).ToList();
            var uns = DB.aspnet_Users.Where(v => mds.Contains(v.MobileAlias) || mds.Contains("86" + v.MobileAlias)).Distinct().ToList();
            ViewBag.Users = uns;

            return ViewOrPartial(m);
        }

        public ActionResult SentSms(ListViewModel<CommonSearchValues, IQueryable<SmsSent>> m = null)
        {
            if (null == m || m.SearchFrom == null)
            {
                m = new ListViewModel<CommonSearchValues, IQueryable<SmsSent>>()
                {
                    PageSize = Services.DefaultPageSize,
                    SearchFrom = new CommonSearchValues(),
                    SearchTo = new CommonSearchValues()
                };
            }
            var d = DB.SmsSents.AsQueryable();

            //if (User.IsInRole("Admin") || User.IsInRole("Engineer")) { ;}
            //else if (User.IsInRole("Doctor")) { var o = SiteUser.UserId.ToString(); d = d.Where(v => v.ReceiverCode == o); }
            if (!string.IsNullOrEmpty(m.SearchFrom.V1)) { var w = DateTime.Parse(m.SearchFrom.V1); d = d.Where(v => v.SentTime >= w); }
            m.ItemCount = d.Count();
            m.PageCount = (int)Math.Ceiling((double)d.Count() / m.PageSize);
            d = d.OrderByDescending(v => v.SentTime);
            m.Data = d;
            return ViewOrPartial(m);
        }
        public ActionResult QizSubjectTree()
        {
            var m = DB.Hospitals_Fixed;
            return PartialView(m);
        }

        public ActionResult BingQuTree()
        {
            var m = DB.Hospitals_Fixed;
            return PartialView(m);
        }

        public ActionResult QizSmsSubjectTree()
        {
            var m = DB.Hospitals_Fixed;
            return PartialView(m);
        }

        [HttpGet]
        public ActionResult QizSessionEdit(string SubjectID, string ID)
        {
            if (string.IsNullOrWhiteSpace(ID))
            {
                var sm = DB.QizSubjects.Where(v => v.ID == SubjectID).First();

                var m = new QizSession() { QizSubject = sm, ID = "-1" };
                foreach (var item in sm.QizSubjectDefines)
                {
                    var qd = new QizSessionDetail();
                    qd.ID = item.ID;
                    qd.QizSession = m;
                    qd.QizSubjectDefine = item;
                    m.QizSessionDetails.Add(qd);//new QizSessionDetail() {QizSessionID="0", QizSubjectDefine=item});
                }
                return View(m);

            }
            else
            {
                var m = DB.QizSessions.Where(v => v.ID == ID).FirstOrDefault();
                return View(m);
            }
        }

        public ActionResult SFReport()
        {
            ViewBag.SubjectCount = DB.QizSubjects.Count();
            ViewBag.ExcpectRecuperCount = DB.QizSubjectObjForDoctors.Select(s => s.Recuper.RecuperID).Distinct().Count();
            ViewBag.ActualRecuperCount = DB.QizSessions.Select(s => s.RecuperID).Distinct().Count();
            ViewBag.TotalSubmitCount = DB.QizSessions.Count();
            //var m = DB.Hospitals_Fixed;
            return PartialView();
        }

        public ActionResult SmsSFReport()
        {
            ViewBag.SubjectCount = DB.QizSubjectObjForDoctors.Select(s => s.QizSmsSubjectID).Distinct().Count();
            ViewBag.ExcpectRecuperCount = DB.QizSubjectObjForDoctors.Select(s => s.RecuperID).Distinct().Count();
            ViewBag.ActualRecuperCount = DB.QizSmsSessions.Where(v => v.SessionStatus == 3).Select(s => s.RecuperID).Distinct().Count();
            ViewBag.TotalSubmitCount = DB.QizSmsSessions.Where(v => v.SessionStatus == 3).Count();


            //var m = DB.Hospitals_Fixed;
            return PartialView(null);
        }
        [HttpGet]
        public ActionResult SysConfig()
        {
            var sss = WebUI.Services.SmsSessionSvc.Instance;
            ViewBag.SmsNextSendTime = sss.NextSendingTime;
            ViewBag.SmsNextReadTime = sss.NextReadingTime;

            //var m = DB.SiteCfgs.First(v => v.ID == "SmsSentHour");
            //var m2 = DB.SiteCfgs.FirstOrDefault(v => v.ID == "errorMessage");
            //if (m2 != null)
            //{
            //    ViewBag.errorMessage = m2.Value;
            //}
            //else
            //{
            //    ViewBag.errorMessage = string.Empty;
            //}
            ////if (m2 == null)
            ////{
            ////    m2 = new SiteCfg() 
            ////    {
            ////        ID = "errorMessage",
            ////        Title = "短信随访错误短信",
            ////        Value = string.Empty
            ////    };
            ////}
            var m = DB.SiteCfgs;
            return PartialView(m);
        }
        [HttpPost]
        public ActionResult SysConfig(SiteCfg m, string MockNow, string submit, string MockUsers, string MockSenderCode, string MockSmsText, string errorMessage, string Act)
        {
            var sss = WebUI.Services.SmsSessionSvc.Instance;
            ViewBag.SmsNextSendTime = sss.NextSendingTime;
            ViewBag.SmsNextReadTime = sss.NextReadingTime;

            if (Act == "执行测试")
            {
                try
                {
                    sss.Debug_IsLog = true;
                    sss.Debug_IsMocking = true;
                    sss.Debug_MockNowValue = DateTime.Parse(MockNow);
                    sss.Debug_MockUserNames = string.IsNullOrEmpty(MockUsers) ? new string[] { "测试用户" } : MockUsers.Split(',');
                    sss.LogString = string.Empty;
                    sss.DoSmsSend();
                }
                catch (Exception ex)
                {
                    sss.Log(ex.StackTrace);
                }
                sss.Debug_IsLog = false;
                sss.Debug_IsMocking = false;
                ViewBag.DebugLog = sss.LogString;
            }
            else if (Act == "回复短信")
            {
                Models.SmsReceived sr = new SmsReceived()
                {
                    ID = DB.NewID(),
                    ReceiverCode = "99999999999",
                    SenderCode = MockSenderCode,
                    ProcStatus = "待处理",
                    ProcTime = DateTime.MaxValue,
                    ReceiverName = " ",
                    SenderName = " ",
                    SentTime = DateTime.Now,
                    TextMessage = MockSmsText
                };

                DB.SmsReceiveds.AddObject(sr);
                DB.SaveChanges();
            }
            else if (Act == "保存")
            {
                var om = DB.SiteCfgs.FirstOrDefault(v => v.ID == m.ID);
                if (om != null)
                {
                    om.Value = m.Value;
                }
                DB.SaveChanges();
            }



            return PartialView(DB.SiteCfgs);
        }

        public ActionResult GetUserByPhone(string PhoneNo)
        {
            var user = DB.aspnet_Users.Where(v => (v.MobileAlias == PhoneNo || v.MobileAlias == "86" + PhoneNo) && v.MainRoleName == "Recuper").FirstOrDefault();
            if (null == user)
            {
                return Content("<div class='error'>此电话为对应任何患者。</div>");
            }
            else
            {
                return RedirectToAction("RecuperEdit", new { ID = user.UserId });
            }
        }
        [HttpGet]
        public ActionResult QizSmsSessionView(string ID)
        {
            var m = DB.QizSmsSessions.Where(v => v.ID == ID).FirstOrDefault();
            return PartialView(m);
        }
    }
}